package org.geektimes.include;


import org.geektimes.injection.component.ComponentBean;
import org.geektimes.injection.context.ComponentContext;
import org.geektimes.injection.context.Initializer.IncludeComponentInitializer;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.Objects;

/**
 * @FileName: JpaComponentInitializer
 * @Description: Jpa组件注册器
 * @Author: MaWenHao
 * @Created: 2021/3/10 - 上午12:44
 */
public class JpaComponentInitializer implements IncludeComponentInitializer {

    private static final String PERSISTENCE_UNIT_NAME = "myJpa";

    private EntityManagerFactory entityManagerFactory;

    private EntityManager entityManager;

    /**
     * 初始化方法,将第三方组件注册到容器上下文对象中
     *
     * @param componentContext
     */
    @Override
    public void init(ComponentContext componentContext) {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        entityManager = entityManagerFactory.createEntityManager();
        componentContext.putComponent(EntityManagerFactory.class.getSimpleName(), new ComponentBean(entityManagerFactory));
        componentContext.putComponent(EntityManager.class.getSimpleName(), new ComponentBean(entityManager));
    }

    /**
     * 组件 销毁方法
     *
     * @param componentContext
     */
    @Override
    public void destroy(ComponentContext componentContext) {
        try {
            if (Objects.nonNull(entityManager)) {
                entityManager.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (Objects.nonNull(entityManagerFactory)) {
                entityManagerFactory.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
